#!/usr/bin/python3
#******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# Author: DisNight
# Create: 2020-12-28
# ******************************************************************************/

from javcra.application.checkpart.check_requires.util.osc_utils import osc_ls_binaries_list, get_all_bin_name_list
from javcra.application.checkpart.check_requires.util.dnf_utils import dnf_download
from javcra.libs.config.global_config import CHECK_REQUIRES_CONFIG

import os
import logging

def perp_download_dir(
    dir_path,
    pkg_name,
    dir_list=CHECK_REQUIRES_CONFIG.UPDATE_RPM_SAVE_SUBPATH
):
    save_dir = {}
    for repo in dir_list:
        repo_path = os.path.join(dir_path, pkg_name, repo)
        try:
            _ = not os.path.exists(repo_path) and os.makedirs(repo_path)
        except Exception as e:
            logging.error("Exception: %s", str(e))
        save_dir[repo] = repo_path
    return save_dir


def download_dnf_rpms(down_dir, bin_list, repos=None, repo_file=None):
    
    for bin_name in bin_list:
        logging.info("try download [%s] in repo[%s]", 
                        bin_name, " ".join(repos) if repos else "default repo")
        dnf_download(down_dir, bin_name, repos, repo_file)


def get_bin_rpmlist(
    pkg_dict,
    obs_prj="openEuler:20.03:LTS",
    repo="standard_aarch64",
    arch="aarch64"
):
    """
    use osc getbinaries to download all bin rpms to get all bin rpms for each pkg
    default download dir: /tmp/update-package/download/pkgname/tmpd
    :return: map
    {
        pkgname0: [bin_rpm_list],
        pkgname1: [bin_rpm_list],
        ...
    }
    """
    pkg2bin_map = {}
    for pkg in pkg_dict:
        if not pkg:
            continue
        pkg_name = pkg.strip().split("src-openEuler/")[-1]
        pkg2bin_map[pkg_name] = []
        data, rc = osc_ls_binaries_list(obs_prj, pkg_name, repo=repo, arch=arch)
        bin_list = get_all_bin_name_list(data)
        logging.info("pkg:[%s] bin_rpms:[%s]", pkg_name, ", ".join(bin_list))
        pkg2bin_map[pkg_name] = {}
        pkg2bin_map[pkg_name]["bin"] = []
        pkg2bin_map[pkg_name]["bin"].extend(bin_list)
        pkg2bin_map[pkg_name]["reason"] = pkg_dict[pkg][0]
        pkg2bin_map[pkg_name]["effected_by"] = pkg_dict[pkg][-1]
    return pkg2bin_map


def download_all_pkgbin(
    save_dir,
    pkg2bin_map,
    old_repos,
    new_repos,
    dirs=CHECK_REQUIRES_CONFIG.UPDATE_RPM_SAVE_SUBPATH,
    repo_file=None
):
    """
    use dnf cmd download all packages' bin rpms
    
    Attribute:

    return:
    """
    for pkg_name in pkg2bin_map:
        paths = perp_download_dir(save_dir, pkg_name, dirs)
        download_dnf_rpms(paths[dirs[0]], pkg2bin_map[pkg_name]["bin"], old_repos, repo_file)
        download_dnf_rpms(paths[dirs[-1]], pkg2bin_map[pkg_name]["bin"], new_repos, repo_file)


def download_required_rpm(save_dir, required_list, repos=None, repo_file=None):
    _ = not os.path.exists(save_dir) and os.makedirs(save_dir)
    for bin_name in required_list:
        logging.info("download required rpm: [%s] in repo[%s]",
                         bin_name, " ".join(repos) if repos else "default repo")
        dnf_download(save_dir, bin_name, repos, repo_file)